<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Rechargerule;
use app\admin\model\Coupon;
use app\admin\model\Image;

use think\Request;

class Memberlevel extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->defaultOrder = 'create_date DESC';

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 充值模板
            $rechargeRules = Rechargerule::where(['status' => 1])->field('id, name')->select();
            $coupons = Coupon::where(['coupon_purpose' => 1, 'status' => 1, 'is_del' => 0])->select();
            // 优惠券类型
            //$couponType = get_coupon_type();

            $this->assign('rechargeRules', $rechargeRules);
            $this->assign('coupons', $coupons);
            //$this->assign('couponType', $couponType);
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $info['coupon_ids'] = explode(',', $info['coupon_ids']);
        $info['payment_rules'] = json_decode($info['payment_rules'], true);

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();
            if ($data['is_payment'] == 1) {
                $ruleJson = [];
                if(isset($data['vip_cost']) && $data['vip_cost']){
                    foreach ($data['vip_cost'] as $key => $val) {
                        if(!trim($val)){
                            continue;
                        }
                        $ruleJson[] = [
                            'vip_cost' => $val * 100,
                            'vip_time' => $data['vip_time'][$key]
                        ];
                    }
                }
                $data['payment_rules'] = json_encode($ruleJson);
            } else {
                $data['payment_rules'] = '';
            }

            if ($data['id']) {
                // Update data
                if($data['status'] == 2){
                    // 该会员等级是否已被使用
                    $usedInfo = $this->isUsed($data['id']);
                    if($usedInfo['code'] != 1){
                        return $this->error($usedInfo['msg']);
                    }
                }

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                $logInfo = $this->admin->name . '更新了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_update';
            } else {
                // Insert data
                $data['id'] = Helper::getUUID();
                $result = $model->save($data);
                $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_insert';
            }

            if($result !== false) {
                // 单图
                if(isset($data['img_id']) && !empty($data['img_id'])){
                    Image::where('id', $data['img_id'])->update(['related_id' => $data['id'], 'related_table' => 'member_level']);
                }

                // Query执行后的操作
                $model->$afterAction($data);

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();

            // 该会员等级是否已被使用
            $usedInfo = $this->isUsed($data['id']);
            if($usedInfo['code'] != 1){
                return $this->error($usedInfo['msg']);
            }

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        // 该会员等级是否已被使用
        $usedInfo = $this->isUsed($id);
        if($usedInfo['code'] != 1){
            return $this->error($usedInfo['msg']);
        }

        $result = $model->where('id', $id)->delete();
        if ($result !== false) {
            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            // 首单立减
            if ($item['is_first_order'] == 1) {
                $item['first_single_reduction'] = '减付款金额的' . $item['first_single_reduction'] . '%';
            } else {
                $item['first_single_reduction'] = '未开启';
            }
            // 消费送积分
            if ($item['is_gives_points'] == 1) {
                $item['integral_quantity'] = '1元送' . $item['integral_quantity'] . '积分';
            } else {
                $item['integral_quantity'] = '未开启';
            }
            // 充值送现金
            if ($item['is_recharge'] == 1) {
                $item['recharge_rule_id'] = Rechargerule::where(['id' => $item['recharge_rule_id']])->value('name');
            } else {
                $item['recharge_rule_id'] = '未开启';
            }
            // 生日送积分
            if ($item['is_birthday_integral'] == 1) {
                //
            } else {
                $item['birthday_quantity'] = '未开启';
            }
            // 优惠券
            if ($item['is_coupon'] == 1) {
                //$countCoupons = Coupon::where(['coupon_type' => ['in', $item['coupon_types']]])->count();
                $countCoupons = count(explode(',', $item['coupon_ids']));
                $item['countCoupons'] = $countCoupons . '张';
            } else {
                $item['countCoupons'] = '未开启';
            }
            // 开通费用
            if ($item['is_payment'] == 1) {
                if($item['payment_rules']){
                    $paymentRules = json_decode($item['payment_rules'], true);
                    $paymentRulesStr = '';
                    foreach($paymentRules as $rule){
                        $paymentRulesStr .= ',' . $rule['vip_cost'] / 100 . '元' . $rule['vip_time'] . '个月';
                    }
                    $item['payment_rules'] = substr($paymentRulesStr, 1);
                }
            } else {
                $item['payment_rules'] = '免费';
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }

        return $where;
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($id){
        if(!$id){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有该会员等级的会员
        $memberWhere = [
            'member_level_id' => $id,
            'm_status' => 1
        ];
        $member = \app\admin\model\Member::where($memberWhere)->find();
        if($member){
            return ['code' => 0, 'msg' => '有使用该会员等级的会员，请先删除会员'];
        }

        return ['code' => 1, 'msg' => ''];
    }

}